<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <input type="file">
    <script>
        console.log('Hello World!');
        const input = document.querySelector('input[type="file"]');
        input.addEventListener('change', (e) => {
            const files = e.target.files[0];
            console.log(files);
            files && senMessage(files)
        });
        const senMessage = (file) => {
            const formData = new FormData();
            formData.append('quality', 80);
            formData.append('files', file);
            console.log(formData.values());
            // http
            // const options = {
            //     method: 'POST',
            //     data:{
            //         files: file,
            //         quality: 80
            //     },
            //     body:formData // 如果是JSON格式
            //     // 或者如果是表单数据: body: new URLSearchParams(formData).toString()
            // };
            // express 
            const options = {
                method: 'POST',
                body:JSON.stringify(formData),
                headers: {
                    'Content-Type': 'application/json'
                },
            };
            console.log(options);
            fetch('http://127.0.0.1:3000/tinypng', options).then(response => {
                console.log('=====》f返回结果1111');
                return response.json();
            }).then(res => {
                console.log('=====》f返回结果2222', res);
                const img = document.createElement('img');
                img.src = 'data:image/png;base64,' + res.pic;
                img.style.width = '200px';
                // img.style.height = '200px';
                document.body.appendChild(img);
            })

        }
        // senMessage()
    </script>
</body>

</html>